#!/bin/bash

set -e

LIST="$1"
VOLUME="$2"

if [ -z "$LIST" -o -z "$VOLUME" ] ; then
	echo "Usage: $0 volume-list-file /volume-path" >&2
	exit 1
fi

mkdir -p "$VOLUME" "$VOLUME-template"
while read i ; do
	parent=$( dirname "$i" )
	if [ -e "$i" -o -L "$i" ] ; then
		tar cf - ".$i" | ( cd "$VOLUME-template" && tar xf - )
	elif [ -z "${i/*\//}" ] ; then
		mkdir -p "$VOLUME-template"/"$i"
	else
		mkdir -p "$VOLUME-template"/"$parent"
	fi
	mkdir -p "$parent"
	rm -rf "$i"
	ln -sv "$VOLUME${i%/}" "${i%/}"
done < "$LIST"

mkdir -p "$VOLUME-template/.rpm-owned"
( rpm -qa --qf '[%{filenames} %{fileflags:hex}\n]' | awk '! / [54].$/ { print $1 }' | sort -u ;
	cd "$VOLUME-template" && find * | sed 's#^#/#' | sort -u ) | sort | uniq -d | while read i ; do
		if [ -f "$VOLUME-template$i" ] ; then
			mkdir -p $( dirname "$VOLUME-template/.rpm-owned$i" )
			ln "$VOLUME-template$i" "$VOLUME-template/.rpm-owned$i"
		fi
	done

mkdir -p "$VOLUME-template/.configfiles"
( rpm -qa --qf '[%{filenames} %{fileflags:hex}\n]' | awk '/[19]$/ { print $1 }' | sort -u ;
	cd "$VOLUME-template" && find * | sed 's#^#/#' | sort -u ) | sort | uniq -d | while read i ; do
		mkdir -p $( dirname "$VOLUME-template/.configfiles$i" )
		ln "$VOLUME-template$i" "$VOLUME-template/.configfiles$i"
	done

mkdir -p "$VOLUME-template/.configfiles-noreplace"
( rpm -qa --qf '[%{filenames} %{fileflags:hex}\n]' | awk '/ [51][19]$/ { print $1 }' | sort -u ;
	cd "$VOLUME-template" && find * | sed 's#^#/#' | sort -u ) | sort | uniq -d | while read i ; do
		mkdir -p $( dirname "$VOLUME-template/.configfiles-noreplace$i" )
		ln "$VOLUME-template/.configfiles$i" "$VOLUME-template/.configfiles-noreplace$i"
	done
